package com.zhenai.bcus.user.filter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.zhenai.bcus.user.constant.UserConstants;
import com.zhenai.bcus.user.context.LoginUserContext;
import com.zhenai.bcus.user.util.StringUtils;
import com.zhenai.bcus.user.vo.LoginUserVO;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.stereotype.Component;


/**
 * 将日志traceId和层级关系以及登录ID传递到下一层
 *
 * @author wangYan
 */
@Component
@Activate(group = CommonConstants.CONSUMER)
public class UserTokenConsumerContextFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            /**
             * 设置userId
             */
            Long userId = LoginUserContext.getUserId();
            if (ObjectUtil.isNotEmpty(userId)) {
                invocation.setAttachment(UserConstants.USER_ID, String.valueOf(userId));
            }

            /**
             * 设置 user
             */
            LoginUserVO userLocalCache = LoginUserContext.getUserLocalCache();
            if (ObjectUtil.isNotEmpty(userLocalCache)) {
                RpcContext.getContext().setAttachment(UserConstants.USER_INFO, JSONObject.toJSONString(userLocalCache));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return invoker.invoke(invocation);
    }
}
